<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>3-单向数据流整体实例</title>
    <script src="js/vue.js"></script>
</head>

<body>
    <div id="app">
        <p>需求:点击按钮,子组件和父组件的数值都变化</p>
        <h1>父组件数值:{{count}}</h1>
        <custom-buy :count="count" @plus-click="plusCount" @minus-click="minusCount"></custom-buy>
    </div>

    <script>
        Vue.component('custom-buy', {
            props: ["count"],
            data: function() {
                return {
                    num: this.count
                }
            },
            template: `
                <div>
                    <h2>我是自定义组件</h2>
                    <div>
                        <span>数量</span>
                        <button @click="changeMinus">-</button>
                        <span>{{cnum}}</span>
                        <button @click="changePlus">+</button>
                    </div>
                </div>
            `,
            methods: {
                changePlus() {
                    // this.count++
                    this.num++
                        this.$emit('plus-click');
                },
                changeMinus() {
                    if (this.num > 0) {
                        this.num--
                    } else {
                        alert('数量不能小于0')
                    }
                    this.$emit('minus-click');
                }
            },
            computed: {
                cnum: function() {
                    return this.num;
                }
            }

        })

        new Vue({
            el: "#app",
            data: {
                count: 0
            },
            methods: {
                plusCount() {
                    this.count++
                },
                minusCount() {
                    if (this.count > 0) {
                        this.count--
                    }
                }
            }
        })
    </script>
</body>

</html>